package com.zuosh.web;

import com.zuosh.common.WebSecurityConfig;
import com.zuosh.domain.User;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zuosh on 2017/4/2.
 */
@Controller
@RequestMapping(value = "/sys")
public class HtmlController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    public static final String VERIFY_CODE = "VERIFY_CODE_%S";

    /**
     * 登陆
     *
     * @param request
     * @param response
     * @param user
     */
    public void login(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {

    }

    @GetMapping("/")
    public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account, Model model) {
        model.addAttribute("name", account);

        String s = String.valueOf(String.format(VERIFY_CODE, RandomStringUtils.random(4)));
        System.out.println(s);
        String test = "hellod";
        stringRedisTemplate.opsForValue().set(test, "1234", 3000);


        return "index";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/loginPost")
    public
    @ResponseBody
    Map<String, Object> loginPost(String account, String password, HttpSession session, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        if (!"123456".equals(password)) {
            map.put("success", false);
            map.put("message", "密码错误");
            return map;
        }
        //add cookie
        Cookie cookie = new Cookie(WebSecurityConfig.SESSION_KEY, "user" + System.currentTimeMillis());
        response.addCookie(cookie);

        // 设置session
        session.setAttribute(WebSecurityConfig.SESSION_KEY, account);

        map.put("success", true);
        map.put("message", "登录成功");
        //add redis
        String s = String.valueOf(String.format(VERIFY_CODE, RandomUtils.nextInt()));
        System.out.println(s);
        String test = "hellod";
        stringRedisTemplate.opsForValue().set(s, "1234", 3000);
//        stringRedisTemplate.opsForValue().set("a","bbb",15, TimeUnit.SECONDS);
//        stringRedisTemplate.opsForValue().set(String.format(VERIFY_CODE, RandomStringUtils.random(4)).toString(), "1234", 3000);
        return map;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session, HttpServletRequest request) {
        // 移除session
        session.removeAttribute(WebSecurityConfig.SESSION_KEY);
        Cookie cookie = getCookie(request, WebSecurityConfig.SESSION_KEY);
        if (cookie != null) {
            cookie.setMaxAge(0);
        }
        return "redirect:/login";
    }

    @GetMapping(value = "hello")
    public String sayHello(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            System.out.println(cookie.getName() + ">>" + cookie.getValue());
//        }

        Enumeration<String> attributeNames = request.getSession().getAttributeNames();
        System.out.println("===>elements");
        if (attributeNames.hasMoreElements()) {
            System.out.println(attributeNames.nextElement());
        }
        modelMap.put("msg", "hello");
//        Cookie cookie = new Cookie(WebSecurityConfig.SESSION_KEY, "user" + System.currentTimeMillis());
//        response.addCookie(cookie);
        return "hello";
    }

    /**
     * get cookie
     *
     * @param request
     * @param name
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(name)) {
                return cookie;
            }
        }
        return null;
    }
}
